package com.kn.knsqlitegenerator.metadata;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.kn.knsqlitegenerator.Column;
import com.kn.knsqlitegenerator.Table;

public class ParseMetaData
{
	public static List<Table> run(String databaseName) throws SQLException
	{
		List<Table> listTables = new ArrayList<Table>();
		Connection connection = DriverManager.getConnection("jdbc:sqlite:"+databaseName);
		DatabaseMetaData databaseMetaData = connection.getMetaData();
		connection.setAutoCommit(false);	
	
		parseTables(databaseMetaData, listTables);
		parseColumns(databaseMetaData, listTables);
		parsePrimaryKeys(databaseMetaData, listTables);
		
		connection.close();
		
		return listTables;
	}

	private static void parsePrimaryKeys(DatabaseMetaData databaseMetaData, List<Table> listTables) throws SQLException
	{
		for (Table table : listTables)
		{
			ResultSet result = databaseMetaData.getPrimaryKeys(null, null, table.name);

			while (result.next())
			{
				String columnName = result.getString(4);

				for (Column column : table.listColumns)
				{
					if (column.name.equals(columnName) == true)
					{
						column.isPrimaryKey = true;
						column.isNullable = false;
					}
				}
			}
		}
	}

	private static void parseColumns(DatabaseMetaData databaseMetaData, List<Table> listTables) throws SQLException
	{
		for (Table table : listTables)
		{
			ResultSet result = databaseMetaData.getColumns(null, null, table.name, null);

			while (result.next())
			{
				Column column = new Column();
				column.name = result.getString(4);
				column.type = result.getInt(5);
				table.listColumns.add(column);
			}
		}
	}

	private static void parseTables(DatabaseMetaData databaseMetaData, List<Table> listTables) throws SQLException
	{
		ResultSet result = databaseMetaData.getTables(null, null, null, new String[] { "TABLE" });

		while (result.next())
		{
			Table table = new Table();
			table.name = result.getString(3);
			listTables.add(table);
		}
	}
}
